package com.webserver5.core;

import com.webserver5.http.EmptyRequestException;
import com.webserver5.http.HttpServletRequest;
import com.webserver5.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.URISyntaxException;

public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            //1.解析请求（将客户端发送过来的请求读取到）
            HttpServletRequest request = new HttpServletRequest(socket);//浏览器发给我们的
            HttpServletResponse response = new HttpServletResponse(socket);//我们回复浏览器的

            //2.处理请求（根据请求内容进行相应处理）
            /*new DispatcherServlet().service(request,response);另一种写法*/
            DispatcherServlet servlet = DispatcherServlet.getInstance();
            servlet.service(request,response);
            //3.发送响应（将处理结果回馈给服务器）
            response.response();

            //定位static目录下index.html


        } catch (IOException e) {
            e.printStackTrace();
        } catch (EmptyRequestException e) {
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws URISyntaxException {
        File rootDir = new File(
                ClientHandler.class.getClassLoader()
                        .getResource(".").toURI()
        );
        //定位static目录（static目录下存放的是所有静态资源）
        File staticDir = new File(rootDir,"static");
        //定位static目录下index.html
        File file = new File(staticDir,"index.html");
        System.out.println("文件是否存在："+file.exists());
        System.out.println(rootDir);
    }

}


